class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def tree2str(self, root):
        """
        :type root: TreeNode
        :rtype: str
        """

        def search(node):
            if node.left:
                left_s = '(' + search(node.left) + ')'
                if node.right:
                    right_s = '(' + search(node.right) + ')'
                else:
                    right_s = ''
            else:
                if node.right:
                    left_s = '()'
                    right_s = '(' + search(node.right) + ')'
                else:
                    left_s = ''
                    right_s = ''
            return str(node.val) + left_s + right_s

        return search(root)
